package org.geektimes.projects.user.oauth2;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * open authentication 2 认证定义
 *
 * @author : lsq
 */
public interface OAuth2Authentication {


	/**
	 * 判断是否支持授权方式
	 *
	 * @param configuration 当前请求的授权配置
	 * @return 如果不支持则为 false 否则为 true 这里将影响到{@link this#authenticated(OAuth2Configuration, HttpServletRequest, HttpServletResponse)}} ()}执行
	 */
	boolean support(OAuth2Configuration configuration);

	/**
	 * 执行认证
	 * @param configuration
	 * @param request
	 * @param response
	 * @throws OAuth2Exception 如果认证失败则抛出{@link OAuth2Exception}
	 */
	Oauth2Token authenticated(OAuth2Configuration configuration , HttpServletRequest request , HttpServletResponse response);


	default String getUrl(OAuth2Configuration configuration ,HttpServletRequest request) {
		final DefaultOAuth2Configuration.ParamConfiguration paramConfiguration = configuration.getParamConfiguration();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder = stringBuilder
				.append(configuration.getAccessTokenUrl())
				.append("?")
				.append(paramConfiguration.getClientId())
				.append("=")
				.append(configuration.getClientId())
				.append("&")
				.append(paramConfiguration.getClientSecret())
				.append("=")
				.append(configuration.getClientSecret())
				.append("&grant_type=authorization_code&")
				.append(OAuth2ConfigurationDelegate.RESPONSE_TYPE)
				.append("=")
				.append(configuration.getAuthCode())
				.append("&redirect_uri=")
				.append(getCallUrl(request) + "?originName=" + configuration.getOriginName());


		return stringBuilder.toString();
	}

	default String getCallUrl(HttpServletRequest request){
		String s = request.getRequestURL().toString();
		String[] split = s.split("//");
		String domain = split[0] +"//" + StringUtils.substringBefore(split[1], "/");
		return domain + OAuth2Handler.PATH;
	}
}
